package cn.juque.redoctopus.client.disruptor.event;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.juque.common.base.DisruptorBody;
import cn.juque.common.base.MqMessageDTO;
import cn.juque.common.disruptor.IBusinessEventService;
import cn.juque.redoctopus.api.dto.LogInfoDTO;
import cn.juque.redoctopus.client.bo.LogEventBO;
import javax.annotation.Resource;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

/**
 * @author nuoka
 * @version 1.0.0
 * <li>IntelliJ IDEA</li>
 * <li></li>
 * @date 2021/8/25 15:38
 **/
@Service("octopusLogEventService")
public class LogEventServiceImpl implements IBusinessEventService {

    public static final String BEAN_NAME="octopusLogEventService";
    private static final Integer MSG_TYPE = 1;
    private static final String[] QUEUES = {"octopus.log1", "octopus.log2"};

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 具体消费者的实现
     *
     * @param disruptorBody 消息体
     */
    @Override
    public void invoke(DisruptorBody disruptorBody) {
        if(null == disruptorBody) {
            return;
        }
        if(disruptorBody instanceof LogEventBO) {
            LogEventBO logEventBO = (LogEventBO) disruptorBody;
            MqMessageDTO<LogInfoDTO> messageDTO = new MqMessageDTO<>();
            messageDTO.setMessageId(UUID.randomUUID(false).toString());
            messageDTO.setTimestamp(System.currentTimeMillis());
            messageDTO.setType(MSG_TYPE);
            messageDTO.setPayload(this.toLogInfoDTO(logEventBO));
            // 发送rabbitmq
            this.rabbitTemplate.convertAndSend("octopus-log", QUEUES[RandomUtil.randomInt(0,1)], messageDTO);
        }
    }

    /**
     * 类型转换
     * @param logEventBO LogEventBO
     * @return LogInfoDTO
     */
    private LogInfoDTO toLogInfoDTO(LogEventBO logEventBO) {
        LogInfoDTO logInfoDTO = new LogInfoDTO();
        logInfoDTO.setTimestamp(logEventBO.getTimestamp());
        logInfoDTO.setServiceNo(logEventBO.getServiceNo());
        logInfoDTO.setServiceName(logEventBO.getServiceName());
        logInfoDTO.setLevel(logEventBO.getLevel());
        logInfoDTO.setMessage(logEventBO.getMessage());
        logInfoDTO.setThrowable(logEventBO.getThrowable());
        logInfoDTO.setIp(logEventBO.getIp());
        logInfoDTO.setThreadId(logEventBO.getThreadId());
        return logInfoDTO;
    }
}
